package main

import (
	"log"
	"os"

	"contrib.go.opencensus.io/exporter/jaeger"
	"gitee.com/huanghua_2017/blade/build"
	lcli "gitee.com/huanghua_2017/blade/client-go/cli"
	cli "github.com/urfave/cli/v2"
	"go.opencensus.io/trace"
)

func SetupJaegerTracing(serviceName string) *jaeger.Exporter {

	if _, ok := os.LookupEnv("JAEGER_ADDR"); !ok {
		return nil
	}
	agentEndpointURI := os.Getenv("JAEGER_ADDR")

	je, err := jaeger.NewExporter(jaeger.Options{
		AgentEndpoint: agentEndpointURI,
		ServiceName:   serviceName,
	})
	if err != nil {
		return nil
	}

	trace.RegisterExporter(je)
	trace.ApplyConfig(trace.Config{
		DefaultSampler: trace.AlwaysSample(),
	})
	return je
}

func main() {
	local := []*cli.Command{
		lcli.RunCmd,
		lcli.InfoCmd,
		lcli.SlaveCmd,
	}

	//os.Setenv("JAEGER_ADDR", "localhost:6831")

	jaeger := SetupJaegerTracing("client-go")
	defer func() {
		if jaeger != nil {
			jaeger.Flush()
		}
	}()

	for _, cmd := range local {
		cmd := cmd
		originBefore := cmd.Before
		cmd.Before = func(cctx *cli.Context) error {
			trace.UnregisterExporter(jaeger)
			jaeger = SetupJaegerTracing("client-go/" + cmd.Name)

			if originBefore != nil {
				return originBefore(cctx)
			}
			return nil
		}
	}

	app := &cli.App{
		Name:    "client-go",
		Usage:   "HTTP代理客户端程序",
		Version: build.Version,
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:    "client_storage",
				EnvVars: []string{"CLIENT_STORAGE"},
				Hidden:  true,
				Value:   "client_storage",
			},
		},

		Commands: local,
	}
	app.Setup()

	if err := app.Run(os.Args); err != nil {
		log.Printf("%+v\n", err)
	}
}
